//
//  YWDownloadCell3.m
//  videoTest3
//
//  Created by jun peng on 2022/8/15.
//

#import "YWDownloadCell3.h"

@interface YWDownloadCell3 ()

@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *situationBtnConstraintWidth;
@property (weak, nonatomic) IBOutlet UIButton *situationBtn;

- (IBAction)situationBtnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

@end


@implementation YWDownloadCell3


+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *ID = @"YWDownloadCell3";
    YWDownloadCell3 *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        // 从xib中加载cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"YWDownloadCell3" owner:nil options:nil] lastObject];
    }
    return cell;
}


- (void)setStatus:(YWDownloadStatus3 *)status{
    _status = status;
    
//    dispatch_async(dispatch_get_main_queue(), ^{
    
    if (![status.PicUrl isKindOfClass:[NSNull class]] && status.PicUrl != nil) {
        
        [self.iconView sd_setImageWithURL:[NSURL URLWithString:status.PicUrl] placeholderImage:[UIImage imageNamed:@""]];
        
    }
    else{
        
        [self.iconView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""]];
        
    }
    
    self.titleLabel.text = status.Title;
    
    self.situationBtn.userInteractionEnabled = YES;
    switch (status.downloadType) {
        case YWDownloadType_Waiting3:
        {
            self.progressView.hidden = NO;
            self.progressLabel.hidden = NO;
            self.situationBtn.hidden = NO;
            self.situationBtnConstraintWidth.constant = 60;
            
            [self.situationBtn setTitle:@"等待中" forState:UIControlStateNormal];
            
            [self.situationBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        }
            break;
        case YWDownloadType_Downloading3:
        {
            self.progressView.hidden = NO;
            self.progressLabel.hidden = NO;
            self.situationBtn.hidden = NO;
            self.situationBtnConstraintWidth.constant = 60;
            
            [self.situationBtn setTitle:@"下载中" forState:UIControlStateNormal];
            
            [self.situationBtn setTitleColor:mainColor forState:UIControlStateNormal];
        }
            break;
        case YWDownloadType_Pause3:
        {
            self.progressView.hidden = NO;
            self.progressLabel.hidden = NO;
            self.situationBtn.hidden = NO;
            self.situationBtnConstraintWidth.constant = 60;
            
            [self.situationBtn setTitle:@"已暂停" forState:UIControlStateNormal];
            
            [self.situationBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        }
            break;
        case YWDownloadType_Finish3:
        {
            self.progressView.hidden = YES;
            self.progressLabel.hidden = YES;
            self.situationBtn.hidden = YES;
            self.situationBtnConstraintWidth.constant = 0;
            
            
            
        }
            break;
        case YWDownloadType_Error3:
        {
            self.progressView.hidden = NO;
            self.progressLabel.hidden = NO;
            self.situationBtn.hidden = NO;
            self.situationBtnConstraintWidth.constant = 60;
            
            [self.situationBtn setTitle:@"下载失败" forState:UIControlStateNormal];
            
            [self.situationBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            
        }
            break;
            
        default: 
        {
            self.progressView.hidden = YES;
            self.progressLabel.hidden = YES;
            self.situationBtn.hidden = YES;
            self.situationBtnConstraintWidth.constant = 0;
            
        }
            break;
    }
    
    
    
    [self.progressView setProgress:status.currentSize*1.0/status.totalSize];
    
    self.progressLabel.text = [NSString stringWithFormat:@"%.0f%%",status.currentSize*1.0/status.totalSize*100];
    
//    //监听progress
//      [self.status addObserver:self forKeyPath:@"currentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionOld context:nil];
//    [self.status addObserver:self forKeyPath:@"totalSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionOld context:nil];
  
//    });
}

//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//
//
////    dispatch_async(dispatch_get_main_queue(), ^{
//
//        //回到主线程，执行UI刷新操作
//        if ([keyPath isEqualToString:@"currentSize"]) {
//
//            if (change[NSKeyValueChangeNewKey]) {
//                NSInteger currentSize = [change[NSKeyValueChangeNewKey] integerValue];
//
//                dispatch_async(dispatch_get_main_queue(), ^{
//
//                    [self.progressView setProgress:currentSize*1.0/self.status.totalSize];
//                });
//            }
//
//        }
//
//        if ([keyPath isEqualToString:@"totalSize"]) {
//
//            if (change[NSKeyValueChangeNewKey]) {
//                NSInteger totalSize = [change[NSKeyValueChangeNewKey] integerValue];
//
//
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.progressView setProgress:self.status.currentSize*1.0/totalSize];
//                });
//            }
//
//        }
//
////    });
//
//
//}

//-(void)dealloc{
////    [self.status removeObserver:self forKeyPath:@"currentSize" context:nil];
////    [self.status removeObserver:self forKeyPath:@"totalSize" context:nil];
//
//}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.iconView.layer.cornerRadius = 5;
    self.iconView.clipsToBounds = YES;
    self.situationBtn.layer.cornerRadius = 12;
    
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadRefreshListNote:) name:YWDownloadRefreshListNote object:nil];
}

-(void)downloadRefreshListNote:(NSNotification *)notification{
    
    NSString *videoUrl = notification.userInfo[YWVideoUrlKey];
    
    NSNumber *progressNum = notification.userInfo[YWProgressKey];

    if ([self.status.VideoUrl isEqualToString:videoUrl]) {
        
        [self.progressView setProgress:progressNum.floatValue];
        
        self.progressLabel.text = [NSString stringWithFormat:@"%.0f%%",progressNum.floatValue*100];
    }
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    
}

-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    
}


- (IBAction)situationBtnClick:(UIButton *)sender {
    
    //这样可以防止双击按钮/快速点击的话造成无法暂停
    sender.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
    
    
    if ([self.delegate respondsToSelector:@selector(downloadCell3:didClickSituationBtnWithStatus:)]) {
        [self.delegate downloadCell3:self didClickSituationBtnWithStatus:self.status];
    }
}

@end
